//
//  NetworkManager+Common.m
//  CustomFramework
//
//  Created by Houge on 2021/5/11.
//

#import "NetworkManager+Common.h"
#import "SDAVAssetExportSession.h"

@implementation NetworkManager (Common)

/// 上传图片
+ (void)uploadImage:(UIImage *)image showLoading:(BOOL)showLoading success:(SuccessBlock)success failure:(FailureBlock)failure {
    if (showLoading) {
        [SVProgressHUD show];
    }
    // 先压缩图片
    [BWMethod compressOriginalImage:image toMaxDataSizeKBytes:500 complete:^(NSData * _Nonnull imageData) {
        UploadParam *uploadParam = [[UploadParam alloc] init];
        uploadParam.data = imageData;
        uploadParam.name = @"file";
        uploadParam.mimeType = @"image/jpeg";
        //获取当前时间（int 时间戳转换）
        NSInteger nowDate = [[NSDate date] timeIntervalSince1970];
        uploadParam.filename = [NSString stringWithFormat:@"%ld.jpg", (long)nowDate];
        
        [[HttpRequest sharedInstance] uploadWithUrlPath:API_UPLOAD_PATH parameters:nil uploadParam:@[uploadParam] progress:^(NSProgress * _Nullable progress) {
            CGFloat progs = progress.completedUnitCount / (double)progress.totalUnitCount;
            NSLog(@"图片上传进度: %f", progs);
        } success:^(id  _Nonnull responseObject) {
            NSLog(@"upload file responseObject ======= %@", responseObject);
            if (showLoading) {
                [SVProgressHUD dismiss];
            }
            if (success) {
                success(responseObject);
            }
        } failure:^(NSString * _Nullable errorCode, NSString * _Nullable errorText) {
            if (showLoading) {
                [SVProgressHUD showErrorWithStatus:errorText];
            }
            if (failure) {
                failure(errorCode, errorText);
            }
        }];
    }];
}

/// 上传图片数组
+ (void)uploadImageList:(NSArray *)imageList showLoading:(BOOL)showLoading complete:(void (^)(NSArray * _Nullable imageUrlArray))completeBlock {
    if (!imageList || imageList.count == 0) {
        return;
    }
    // 准备保存结果的数组，元素个数与上传的图片个数相同，先用 NSNull 占位
    NSMutableArray *result = [NSMutableArray array];
    NSMutableArray *completedResult = [NSMutableArray array];
    for (int i = 0; i < imageList.count; i++) {
        [result addObject:[NSNull null]];
    }
    
    dispatch_group_t group = dispatch_group_create();
    
    if (showLoading) {
        [SVProgressHUD showMessage:[NSString stringWithFormat:@"图片上传中：1/%ld", (long)imageList.count]];
    }
    
    for (NSInteger i = 0; i < imageList.count; i++) {
        dispatch_group_enter(group);
        [self uploadImage:imageList[i] showLoading:NO success:^(id  _Nullable responseObject) {
            NSString *urlStr = responseObject[@"url"];
            // 上传成功
            // NSMutableArray 是线程不安全的，所以加个同步锁
            @synchronized (result) {
                result[i] = urlStr;
                [completedResult addObject:urlStr];
                
                // 此处设置上传进度条
                dispatch_async(dispatch_get_main_queue(), ^{
                    float progress = 1.0 * completedResult.count / imageList.count;
                    NSLog(@"上传进度%.2f", progress);
                    if (showLoading) {
                        [SVProgressHUD showMessage:[NSString stringWithFormat:@"图片上传中：%ld/%ld", (long)completedResult.count, (long)imageList.count]];
                    }
                    if ((completedResult.count == imageList.count)) {
                        [SVProgressHUD dismiss];
                    }
                });
            }
            dispatch_group_leave(group);
            NSLog(@"第 %d 张图片上传成功: %@", (int)i + 1, responseObject);
        } failure:^(NSString * _Nullable errorCode, NSString * _Nullable errorText) {
            dispatch_group_leave(group);
            NSLog(@"第 %d 张图片上传失败: %@", (int)i + 1, errorText);
            if (showLoading) {
                [SVProgressHUD showErrorWithStatus:@"上传图片失败!"];
            }
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"上传完成!");
        if (showLoading) {
            [SVProgressHUD showSuccessWithStatus:@"图片上传完成"];
        }
        if (completeBlock) {
            completeBlock([NSArray arrayWithArray:result]);
        }
    });
}

/// 上传视频
+ (void)uploadVideoWithURL:(NSURL *)videoPath success:(SuccessBlock)success failure:(FailureBlock)failure {
    [SVProgressHUD show];
    NSLog(@"视频压缩前大小 %f MB",[[NSData dataWithContentsOfURL:videoPath] length]/1024.00 /1024.00);
    AVAsset *asset = [AVAsset assetWithURL:videoPath];
    AVURLAsset *videoAsset = (AVURLAsset *)asset;
    // 先压缩视频
    [SDAVAssetExportSession startExportVideoWithVideoAsset:videoAsset timeRange:kCMTimeRangeZero presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
        NSLog(@"视频压缩后大小 %f MB",[[NSData dataWithContentsOfFile:outputPath] length]/1024.00 /1024.00);
        // 再上传视频
        dispatch_async(dispatch_get_main_queue(), ^{
            UploadParam *uploadParam = [[UploadParam alloc] init];
            uploadParam.data = [NSData dataWithContentsOfFile:outputPath];
            uploadParam.name = @"file";
            uploadParam.mimeType = @"video/mp4";
            //获取当前时间（int 时间戳转换）
            NSInteger nowDate = [[NSDate date] timeIntervalSince1970];
            uploadParam.filename = [NSString stringWithFormat:@"%ld.mp4", (long)nowDate];

            NSDictionary *params = [self setupParamsDictWithModule:@"UploadVideo" interface:@"1000" dataDict:nil];

            [[HttpRequest sharedInstance] uploadWithUrlPath:API_UPLOAD_PATH parameters:params uploadParam:@[uploadParam] progress:^(NSProgress * _Nullable progress) {
                CGFloat progs = progress.completedUnitCount / (double)progress.totalUnitCount;
                NSLog(@"视频上传进度: %f", progs);
                [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"视频上传中: %.0f%%", progs * 100]];

            } success:^(id  _Nonnull responseObject) {
                NSLog(@"upload file responseObject ======= %@", responseObject);
                [SVProgressHUD dismiss];

                if (success) {
                    success(responseObject);
                }

            } failure:^(NSString * _Nullable errorCode, NSString * _Nullable errorText) {
                [SVProgressHUD showErrorWithStatus:errorText];
                if (failure) {
                    failure(errorCode, errorText);
                }
            }];
        });
    } failure:^(NSString *errorMessage, NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"压缩失败 %@",errorMessage);
    }];
}

/// 下载文件
+ (void)downloadFileWithURL:(NSString *)fileUrl saveFilePath:(nullable NSString *)saveFilePath showLoading:(BOOL)showLoading success:(DownloadSuccessBlock)success failure:(FailureBlock)failure {
    if (showLoading) {
        [SVProgressHUD show];
    }
    [[HttpRequest sharedInstance] downLoadWithUrlString:fileUrl saveFilePath:saveFilePath progress:^(NSProgress * _Nullable progress) {
        CGFloat progs = progress.completedUnitCount / (double)progress.totalUnitCount;
        NSLog(@"%@ --- 下载进度: %f", fileUrl, progs);
        if (showLoading) {
            [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"正在下载中: %.0f%%", progs * 100]];
        }
    } success:^(NSString * _Nullable filePath) {
        if (showLoading) {
            [SVProgressHUD dismiss];
        }
        if (success) {
            success(filePath);
        }
    } failure:^(NSString * _Nullable errorCode, NSString * _Nullable errorText) {
        if (showLoading && !kStringIsEmpty(errorText)) {
            [SVProgressHUD showErrorWithStatus:errorText];
        }
        if (failure) {
            failure(errorCode, errorText);
        }
    }];
}

@end
